package com.feizhi.common.search.index.action;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

import com.feizhi.common.search.exception.SearchException;
import com.feizhi.common.search.index.IndexConstants;
import com.feizhi.common.search.index.LuceneWork;

public class DeleteIndexAction extends AbstractIndexAction implements IndexAction {

    private static final Log LOG = LogFactory.getLog(DeleteIndexAction.class);

    @Override
    public void performAction(final LuceneWork work) {
        final Class<?> entityType = work.getEntityType();
        final Serializable id = work.getId();
        LOG.trace("Removing " + work + " by query.");

        final BooleanQuery entityDeletionQuery = new BooleanQuery();
        
        final Term classNameQueryTerm = new Term(IndexConstants.TYPE_CLASS, entityType.getName());
        final TermQuery classNameQuery = new TermQuery(classNameQueryTerm);
        entityDeletionQuery.add(classNameQuery, BooleanClause.Occur.MUST);

        final Term idTerm = new Term(IndexConstants.TYPE_ID, id.toString());
        final Query idQueryTerm = new TermQuery(idTerm);
        entityDeletionQuery.add(idQueryTerm, BooleanClause.Occur.MUST);

        try {
            writer.deleteDocuments(entityDeletionQuery);
        } catch (final Exception e) {
            final String message = "Unable to remove " + work + " from index.";
            throw new SearchException(message, e);
        }
    }

}
